﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Entity;
using Controller;
using System.Collections;

namespace Web
{
    public partial class MakeVendorInvoice : System.Web.UI.Page
    {
        StorageEntity storageEntity=new StorageEntity();
        IList<StorageEntity> storageEntities=new List<StorageEntity>();
        VendorPOEntity vendorPOEntity=new VendorPOEntity();
        VendorPOItemEntity vendorPOItemEntity=new VendorPOItemEntity();
        VendorPOController vendorPOController=new VendorPOController();
        VendorController vendorController=new VendorController();
        VendorPOItemController vendorPOItemController=new VendorPOItemController();
        ProductController productController=new ProductController();
        Helper helper = new Helper();
        private StorageController storageController=new StorageController();
        
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                Session["VendorInvoiceItem"] = null;
                IList<VendorEntity> vendorEntities = vendorController.FindAllVendorEntities();
                VendorDropDownList.DataSource = vendorEntities;
                VendorDropDownList.DataTextField = "ShortName";
                VendorDropDownList.DataValueField = "Id";
                VendorDropDownList.DataBind();

                this.BindVendorPODropDownList();
                this.BindPOItemAndRequestedDateDropDownList();

                if(POItemAndRequestedDateDropDownList.SelectedIndex==0)
                {
                    InsertButton.Enabled = false;
                }

                DateTextBox_CalendarExtender.SelectedDate = System.DateTime.Now;
            }

            this.PreRender += new EventHandler(UpdateFlashMessage);
        }

        private void UpdateFlashMessage(object sender, EventArgs e)
        {
            helper.ShowFlashMessage(FlashMessageLabel);
        }

        private void BindVendorPODropDownList()
        {
            int vendorId = Convert.ToInt32(VendorDropDownList.SelectedValue);

            //IList<VendorPOEntity> vendorPOEntities = vendorPOController.findVendorPOByVendorIdAndStatus(vendorId, "new");
            IList<VendorPOEntity> vendorPOEntities = vendorPOController.findVendorPOByVendor(vendorId);
            VendorPODropDownList.DataSource = vendorPOEntities;
            VendorPODropDownList.DataTextField = "No";
            VendorPODropDownList.DataValueField = "Id";
            VendorPODropDownList.DataBind();
        }

        

        protected void InsertButton_Click(object sender, EventArgs e)
        {
            if (Session["VendorInvoiceItem"] == null)
            {
                this.ConstructStorageEntity();
                
                
            }
            else
            {
                storageEntities = Session["VendorInvoiceItem"] as IList<StorageEntity>;
                this.ConstructStorageEntity();
                


            }
            Session["VendorInvoiceItem"] = storageEntities;
            InvoiceItemGridView.DataSource = storageEntities;
            InvoiceItemGridView.DataBind();


        }

        private void ConstructStorageEntity()
        {
            storageEntity.PoNo = VendorPODropDownList.SelectedItem.Text;
            storageEntity.Quantity = Convert.ToInt32(QuantityTextBox.Text);
            storageEntity.UnitPrice = Convert.ToDecimal(UnitPriceLabel.Text);
            VendorPOItemEntity vendorPoItemEntity = this.ConstructVendorPOItemEntity();
            storageEntity.ProductId = vendorPoItemEntity.ProductId;
            storageEntity.ProductNo = vendorPoItemEntity.ProductNo;
            storageEntity.ProductName = vendorPoItemEntity.ProductName;
            storageEntity.Amount = storageEntity.Quantity * storageEntity.UnitPrice;
            storageEntity.RequestedDate = vendorPoItemEntity.RequestDate;
            storageEntity.VendPoItemId = vendorPoItemEntity.Id;
            storageEntity.Revision = vendorPoItemEntity.Rev;
            //storageEntity.StockItemId = Convert.ToInt32(BatchNoDropDownList.SelectedValue);
            storageEntity.VendorId = vendorPoItemEntity.VendorId;
            storageEntity.BatchNo = vendorPoItemEntity.VendorNumber+BatchNoTextBox.Text.Trim();
            storageEntity.RequestQty = vendorPoItemEntity.RequestQty;
            storageEntity.VendorName = vendorPoItemEntity.VendorName;
            storageEntities.Add(storageEntity);
        }

        protected void VendorPODropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindPOItemAndRequestedDateDropDownList();
        }

        protected void BindPOItemAndRequestedDateDropDownList()
        {
            int vendorPOId = Convert.ToInt32(VendorPODropDownList.SelectedValue);
            VendorPOController vendorPoController = new VendorPOController();
            vendorPOEntity = vendorPoController.findVendorPOById(vendorPOId);
            int vendorId = vendorPOEntity.VendId;
            VendorEntity vendorEntity = vendorController.findVendorByVendorId(vendorId);
            string vendorName = vendorEntity.Name;
            IList<VendorPOItemEntity> vendorPOItemEntities = vendorPOItemController.findUncompletedVendorPOItemsByVendorPOId(vendorPOId);
            POItemAndRequestedDateDropDownList.DataSource = vendorPOItemEntities;
            POItemAndRequestedDateDropDownList.DataTextField = "ItemAndRequestedDate";
            POItemAndRequestedDateDropDownList.DataValueField = "Id";
            POItemAndRequestedDateDropDownList.DataBind();
            POItemAndRequestedDateDropDownList.Items.Insert(0, new ListItem("--Select Item--", "0"));
        }

        protected void POItemAndRequestedDateDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (POItemAndRequestedDateDropDownList.SelectedIndex != 0)
            {
                VendorPOItemEntity vendorPoItemEntity = this.ConstructVendorPOItemEntity();
                UnitPriceLabel.Text = vendorPoItemEntity.Price.ToString();
                QuantityTextBox.Text = vendorPoItemEntity.RequestQty.ToString();
                InsertButton.Enabled = true;

                //int productId = vendorPoItemEntity.ProductId;
                //StockItemController stockItemController = new StockItemController();
                //IList<StockItemEntity> batchList = stockItemController.FindBatchNoByProductId(productId);
                //BatchNoDropDownList.DataSource = batchList;
                //BatchNoDropDownList.DataValueField = "Id";
                //BatchNoDropDownList.DataTextField = "BatchNo";
                //BatchNoDropDownList.DataBind();
            }
            else
            {
                InsertButton.Enabled = false; 
            }
        }

        private  VendorPOItemEntity ConstructVendorPOItemEntity()
        {
            if (POItemAndRequestedDateDropDownList.SelectedIndex != 0)
            {
                int poItemId = Convert.ToInt32(POItemAndRequestedDateDropDownList.SelectedValue);
                VendorPOItemEntity vendorPoItemEntity = vendorPOItemController.findVendorPOItemByVendorPOItemId(poItemId);
                return vendorPoItemEntity;
            }
            else
            {
                return null;
            }

        }
        protected void DeleteVendorInvoiceItemButton_Click(object sender, EventArgs e)
        {
            try
            {
                int rowIndex = ((GridViewRow)((Button)sender).NamingContainer).RowIndex;
                IList<StorageEntity> storageEntities = Session["VendorInvoiceItem"] as IList<StorageEntity>;
                storageEntities.RemoveAt(rowIndex);
                InvoiceItemGridView.DataSource = storageEntities;
                InvoiceItemGridView.DataBind();
                Session["VendorInvoiceItem"] = storageEntities;
            }
            catch (Exception)
            {
                Session["FlashMessage"] = "Error: Cannot Delete Item!";
                Session["FlashMessageType"] = "error";
            }
        }

        protected void AddVendorInvoiceButton_Click(object sender, EventArgs e)
        {
            int count = InvoiceItemGridView.Rows.Count;
            if (count > 0)
            {

                IList<StorageEntity> storageEntities = Session["VendorInvoiceItem"] as IList<StorageEntity>;
                int paid = 0;
                string stockInNo = InvoiceNoTextBox.Text;
                int vendId = storageEntities.ElementAt(0).VendorId;
                DateTime date = Convert.ToDateTime(DateTextBox.Text);
                StockInController stockInController = new StockInController();
                //add stock in record.
                int stockInId = stockInController.addStockIn(stockInNo, vendId, date);
                int vendorPOId = Convert.ToInt32(VendorPODropDownList.SelectedValue);
                if (PaidCheckBox.Checked)
                {
                    paid = 1;
                }
                VendorInvoiceController vendorInvoiceController = new VendorInvoiceController();
                //add vendor invoice record.
                vendorInvoiceController.addVendorInvoice(stockInNo, stockInId, paid);

                //add storage records, update product stock, update vendor po item complete qty and status, update vendor po status.

                
                foreach (StorageEntity s in storageEntities)
                {

                    int productId = s.ProductId;
                    //int stockItemId = s.StockItemId;
                    int qty = s.Quantity;
                    int vendPoItemId = s.VendPoItemId;
                    //add stockItem(Batch No!!!!) or update stockItem(same batchNo),add storage and update product stock.
                    StockItemController stockItemController=new StockItemController();
                    int stockItemId = stockItemController.AddStockItem(s);
                    storageController.addStorage(stockInId, stockItemId, qty, vendPoItemId);
                    productController.updateStock(productId, qty);
                    
                    //check complete qty, if complete qyt== request qty, set staust to complete
                    int completeQty = vendorPOItemController.updateVendorPOItem(vendPoItemId, qty);
                    VendorPOItemEntity vendorPoItemEntity =
                        vendorPOItemController.findVendorPOItemByVendorPOItemId(vendPoItemId);
                    if (completeQty >= vendorPoItemEntity.RequestQty)
                    {
                        DateTime completeDate = Convert.ToDateTime(DateTextBox.Text);
                        vendorPOItemController.updateVendorPOItem(vendPoItemId, "completed",completeDate);
                    }
                    else
                    {
                        if(completeQty<vendorPoItemEntity.RequestQty)
                        {
                            DateTime completeDate = Convert.ToDateTime(DateTextBox.Text);
                            vendorPOItemController.updateVendorPOItem(vendPoItemId, "ongoing", completeDate);
                        }
                    }

                }
                IList<VendorPOItemEntity> vendorPoItemEntities = new List<VendorPOItemEntity>();
                vendorPoItemEntities = vendorPOItemController.findVendorPOItemsByVendorPOId(vendorPOId);
                int unCompleteCount = 0;
                foreach (VendorPOItemEntity vendorPoItemEntity in vendorPoItemEntities)
                {

                    if (vendorPoItemEntity.Status != "completed")
                    {
                        unCompleteCount++;

                    }

                }
                if (unCompleteCount == 0)
                {
                    vendorPOController.updateVendorPOStatus(vendorPOId, "completed");
                }
                else
                {
                    vendorPOController.updateVendorPOStatus(vendorPOId, "ongoing");
                }
                Session["VendorInvoiceItem"] = null;
                //ClientScript.RegisterStartupScript(this.Page.GetType(), "Success!",
                //                                   "if(window.confirm('You have add vendor invoice successfully! Go back and refresh page?')){window.location.href='VendorInvoice.aspx';}",
                //                                   true);
                //SuccessfulLabel.Text = "You have add vendor invoice successfully!";
                Session["FlashMessage"] = "Success: Add Vendor Invoice Successful!";
                Session["FlashMessageType"] = "success";
            }
            else
            {
                //ClientScript.RegisterStartupScript(this.Page.GetType(), "No insert!", "alert('Please insert item(s).')", true);
                //SuccessfulLabel.Text = "Please insert item(s).";
                Session["FlashMessage"] = "Error: Please insert item(s).";
                Session["FlashMessageType"] = "error";
            }


        }

        protected void VendorDropDownList_SelectedIndexChanged(object sender, EventArgs e)
        {
            this.BindVendorPODropDownList();
        }
    }
}